#include <QDebug>
#include <string>
#include <QtXlsx>
#include "exportxlsx.h"
#include "classmate.h"
#include <QThread>

using namespace QXlsx;

exportxlsx::exportxlsx(QObject *parent) : QObject(parent)
{
    lang=Zh;
}

void exportxlsx::run(){
    bool hasItem=false;
    if(Zh==lang){
        foreach (auto item, classMateList) {
            if(item.checked_){
                create(item);
                hasItem=true;
            }
        }
    }
    else if (En==lang) {
        if(!classMateList.isEmpty()){
            createEn();
            hasItem=true;
        }
    }
    //QThread::sleep(1);
    emit idle();
    if(hasItem)
        emit end();

}
void exportxlsx::setLang(LANG langName){
    lang=langName;
}
void exportxlsx::setClassMateList(const ClassMate &aFile){
    classMateList.append(aFile);
}

int exportxlsx::create(const ClassMate &aFile){

    qDebug()<<"begin create";
    //"../Database/DataRetest/30_1_CL2030 Test Plan.xml"
    if(doc.LoadFile(aFile.fullPath_.toLocal8Bit())){
        qDebug()<<"file load error";
        doc.PrintError();
        return 1;
    }
    QString dir_str = "../Excel";//save path

    QXlsx::Document xlsx;
    Format format;
    format.setHorizontalAlignment(Format::AlignHCenter);
    format.setVerticalAlignment(Format::AlignVCenter);

    root=doc.RootElement();
    QString deviceNo(root->Attribute("DeviceID"));

    xlsx.write("A1", deviceNo.append("号精密CT测试数据"));
    xlsx.mergeCells("A1:T1",format);

    Format format1;
    format1.setFontBold(true);
    format1.setHorizontalAlignment(Format::AlignHCenter);
    format1.setVerticalAlignment(Format::AlignVCenter);
    format1.setBorderStyle(QXlsx::Format::BorderThin);

    xlsx.write("A2","量程");
    xlsx.mergeCells("A2:A3",format1);

    xlsx.write("B2","输入电流(A)");
    xlsx.mergeCells("B2:B3",format1);

    xlsx.write("C2","标准电流(mA,A)");
    xlsx.mergeCells("C2:E2",format1);
    xlsx.write("C3","A相",format1);
    xlsx.write("D3","B相",format1);
    xlsx.write("E3","C相",format1);

    xlsx.write("F2","实测电流(mA,A)");
    xlsx.mergeCells("F2:H2",format1);
    xlsx.write("F3","A相",format1);
    xlsx.write("G3","B相",format1);
    xlsx.write("H3","C相",format1);

    xlsx.write("I2","幅值误差(%)");
    xlsx.mergeCells("I2:K2",format1);
    xlsx.write("I3","A相",format1);
    xlsx.write("J3","B相",format1);
    xlsx.write("K3","C相",format1);

    xlsx.write("L2","标准相位(°)");
    xlsx.mergeCells("L2:N2",format1);
    xlsx.write("L3","A相",format1);
    xlsx.write("M3","B相",format1);
    xlsx.write("N3","C相",format1);

    xlsx.write("O2","实测相位(°)");
    xlsx.mergeCells("O2:Q2",format1);
    xlsx.write("O3","A相",format1);
    xlsx.write("P3","B相",format1);
    xlsx.write("Q3","C相",format1);

    xlsx.write("R2","相位误差(%)");
    xlsx.mergeCells("R2:T2",format1);
    xlsx.write("R3","A相",format1);
    xlsx.write("S3","B相",format1);
    xlsx.write("T3","C相",format1);

    Format format2;
    format2.setHorizontalAlignment(Format::AlignRight);
    format2.setVerticalAlignment(Format::AlignVCenter);
    format2.setBorderStyle(QXlsx::Format::BorderThin);

    tinyxml2::XMLElement *firstItems = root->FirstChildElement("Items");
    tinyxml2::XMLElement *firstGroupOfItems = firstItems->FirstChildElement("GroupData");
    tinyxml2::XMLElement *firstItemsOfGroup = firstGroupOfItems->FirstChildElement("Items");
    tinyxml2::XMLElement *itemData=firstItemsOfGroup->FirstChildElement();
    QString current("5A");
    QString percent("100%");
    QString inCurrent("5A");
    QString innerValue;
    int row=4;
    int col=1;
    while (itemData) {
        current=QString(itemData->Attribute("Parameter")).split("_")[3];
        percent=QString(itemData->Attribute("Parameter")).split("_")[4];
        qDebug()<<current<<" "<<percent;
        col=1;
        xlsx.write(row,col,current,format2);
        inCurrent=QString("%1").arg(current.replace("A","").replace("mA","").toFloat() * percent.remove('%').toFloat() / 100.0);
        xlsx.write(row,++col,inCurrent,format2);

        innerValue=itemData->Attribute("ReferenceValue");
        qDebug()<<innerValue;
        auto tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        innerValue=itemData->Attribute("MeasuredValue");
        qDebug()<<innerValue;
        tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        innerValue=itemData->Attribute("ErrorValue");
        qDebug()<<innerValue;
        tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        innerValue=itemData->Attribute("ReferenceValue2");
        qDebug()<<innerValue;
        tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        innerValue=itemData->Attribute("MeasuredValue2");
        qDebug()<<innerValue;
        tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        innerValue=itemData->Attribute("ErrorValue2");
        qDebug()<<innerValue;
        tempAry=innerValue.split(";");
        for (auto istr:tempAry) {
            xlsx.write(row,++col,istr,format2);
        }

        itemData=itemData->NextSiblingElement();
        ++row;
    }
    QDir dir;
    if (!dir.exists(dir_str))
        dir.mkpath(dir_str);

    xlsx.saveAs(dir_str + "/" + deviceNo + ".xlsx");
    qDebug()<<"end create";
    return 1;
}

int exportxlsx::createEn(){
    QString dir_str = "../Excel";//save path

    Format format;
    format.setHorizontalAlignment(Format::AlignHCenter);
    format.setVerticalAlignment(Format::AlignVCenter);
    format.setBorderStyle(QXlsx::Format::BorderThin);

    Format format1;
    format1.setFontBold(true);
    format1.setHorizontalAlignment(Format::AlignHCenter);
    format1.setVerticalAlignment(Format::AlignVCenter);
    format1.setBorderStyle(QXlsx::Format::BorderThin);

    Format format2;
    format2.setHorizontalAlignment(Format::AlignRight);
    format2.setVerticalAlignment(Format::AlignVCenter);
    format2.setBorderStyle(QXlsx::Format::BorderThin);

    QXlsx::Document xlsx;
    xlsx.write(2,1,"ICT Serial No.");
    xlsx.mergeCells(CellRange(2,1,3,1),format1);
    int count=0;
    int rowOffset=0;
    bool onceHeader=false;
    foreach (auto item, classMateList) {
        if(item.checked_){
            if(doc.LoadFile(item.fullPath_.toLocal8Bit())){
                qDebug()<<"file load error";
                doc.PrintError();
                doc.Clear();
                continue;
            }

            root=doc.RootElement();
            QString deviceNo(root->Attribute("DeviceID"));

            xlsx.write(4+rowOffset,1, deviceNo,format);

            tinyxml2::XMLElement *firstItems = root->FirstChildElement("Items");
            tinyxml2::XMLElement *firstGroupOfItems = firstItems->FirstChildElement("GroupData");
            tinyxml2::XMLElement *firstItemsOfGroup = firstGroupOfItems->FirstChildElement("Items");
            tinyxml2::XMLElement *itemData=firstItemsOfGroup->FirstChildElement();

            int colOffset=0;
            int col=1;
            QString current("5A");
            QString percent("100%");
            QString inCurrent("5A");
            QString innerValue;

            while (itemData) {
                if(!onceHeader){
                    current=QString(itemData->Attribute("Parameter")).split("_")[3];
                    percent=QString(itemData->Attribute("Parameter")).split("_")[4];
                    qDebug()<<current<<" "<<percent;

                    inCurrent=QString("%1A").arg(current.replace("A","").replace("mA","").toFloat() * percent.remove('%').toFloat() / 100.0);
                    xlsx.write(1,2+colOffset,inCurrent);
                    xlsx.mergeCells(CellRange(1,2+colOffset,1,7+colOffset),format1);

                    xlsx.write(2,2+colOffset,"Ratio error (%)");
                    xlsx.mergeCells(CellRange(2,2+colOffset,2,4+colOffset),format1);
                    xlsx.write(3,2+colOffset,"L1",format1);
                    xlsx.write(3,3+colOffset,"L2",format1);
                    xlsx.write(3,4+colOffset,"L3",format1);

                    xlsx.write(2,5+colOffset,"Phase displacement [min]");
                    xlsx.mergeCells(CellRange(2,5+colOffset,2,7+colOffset),format1);
                    xlsx.write(3,5+colOffset,"L1",format1);
                    xlsx.write(3,6+colOffset,"L2",format1);
                    xlsx.write(3,7+colOffset,"L3",format1);
                }
                innerValue=itemData->Attribute("ErrorValue");
                qDebug()<<innerValue;
                auto tempAry=innerValue.split(";");
                col=1+colOffset;
                for (auto istr:tempAry) {
                    xlsx.write(4+rowOffset,++col,istr,format2);
                }

                innerValue=itemData->Attribute("ErrorValue2");
                qDebug()<<innerValue;
                tempAry=innerValue.split(";");
                col=4+colOffset;
                for (auto istr:tempAry) {
                    xlsx.write(4+rowOffset,++col,istr,format2);
                }

                itemData=itemData->NextSiblingElement();
                colOffset+=6;
            }//while
            onceHeader=true;
            doc.Clear();
        }//if
        ++count;
        ++rowOffset;
    }//foreach
    QDir dir;
    if (!dir.exists(dir_str))
        dir.mkpath(dir_str);

    xlsx.saveAs(dir_str + "/CTTest(" + QString::number(count) + ")" + QDateTime::currentDateTime().toString("yyyy-MM-dd") + ".xlsx");
    qDebug()<<"end create";
    return 1;
}
